package cn.edu.sdjzu.xg.bysj.controller.authority;


import cn.edu.sdjzu.xg.bysj.security.ActorAssRole;
import cn.edu.sdjzu.xg.bysj.security.Actor;
import cn.edu.sdjzu.xg.bysj.security.Role;
import cn.edu.sdjzu.xg.bysj.domain.User;
import cn.edu.sdjzu.xg.bysj.security.ActorAssRoleService;
import cn.edu.sdjzu.xg.bysj.security.ActorService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import cn.edu.sdjzu.xg.bysj.util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.TreeSet;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import  cn.edu.sdjzu.xg.bysj.util.JwtUtil;


@WebServlet("/login.ctl")
public class LoginController extends HttpServlet {
    private static final Logger log = LogManager.getLogger(LoginController.class);

    /**
     *{"username":"s1","password":"s1"}
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //创建JSON对象respMessage_jsonObj，以便往前端响应信息
        JSONObject respMessage_jsonObj = new JSONObject();
        //设置响应字符编码为UTF-8
        response.setContentType("application/json;charset=UTF-8");
        //将request body转换为JSON字串
        String actor_json = JSONUtil.getJSON(request);
        //将JSON字串解析为User对象
        User userToLogin =  JSON.parseObject(actor_json, User.class);

        //创建JSON对象message，以便往前端响应信息
        JSONObject message = new JSONObject();

        try {
            //根据用户名和密码信息，获得当前登录的参与者
            Actor currentActor = ActorService.getInstance().login(userToLogin);
            if (currentActor == null) {
                message.put("message", "用户名或密码不匹配");
                log.debug("用户名或密码不匹配");
            } else {
                log.info("info");
                log.debug("用户名或密码匹配");
                //根据得到参与者拥有所有的“参与者-角色”数据
                Collection<ActorAssRole> actorAssRoleCollection = ActorAssRoleService.getInstance().findAll(currentActor);
                Collection<Role> roles = new TreeSet<>();
                //将该参与者拥有的所有角色（包含相应的权限）
                for (ActorAssRole actorAssRole : actorAssRoleCollection) {
                    Role role = actorAssRole.getRole();
                    roles.add(role);
                }
                message.put("actor", currentActor);
                message.put("roles", roles);

                String token = JwtUtil.createToken(currentActor, 1);
                //将token放入响应头
                response.setHeader("token",token);

                //输出JSON字串时，屏蔽某些字段
                SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
                //FastJson生成JSON数据时，排除"department"字段
                filter.getExcludes().add("no");
                filter.getExcludes().add("department");
                //根据filter的设置,响应数据
                response.getWriter().println(JSON.toJSONString(message, filter));

            }
        } catch (SQLException e) {
            message.put("message", "数据库操作异常");
            //响应message到前端
            response.getWriter().println(message);
            e.printStackTrace();
        } catch (Exception e) {
            message.put("message", "网络异常");
            //响应message到前端
            response.getWriter().println(message);
            e.printStackTrace();
        }
    }
}
